package com.xujie.sportsmeeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xujie.sportsmeeting.common.exception.BusinessException;
import com.xujie.sportsmeeting.common.result.ResultCode;
import com.xujie.sportsmeeting.entity.SystemNotice;
import com.xujie.sportsmeeting.mapper.SystemNoticeMapper;
import com.xujie.sportsmeeting.service.NoticeReadRecordService;
import com.xujie.sportsmeeting.service.SystemNoticeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 系统公告服务实现类
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SystemNoticeServiceImpl extends ServiceImpl<SystemNoticeMapper, SystemNotice> implements SystemNoticeService {

    private final NoticeReadRecordService noticeReadRecordService;

    @Override
    @Transactional
    public boolean publishNotice(SystemNotice notice) {
        // 设置发布状态和时间
        notice.setPublishStatus(1);
        notice.setPublishTime(LocalDateTime.now());
        
        // 设置默认值
        if (notice.getPriority() == null) {
            notice.setPriority(2); // 默认中等优先级
        }
        if (notice.getIsTop() == null) {
            notice.setIsTop(0); // 默认不置顶
        }
        // 移除了targetUserType和needConfirm字段的设置
        if (notice.getReadCount() == null) {
            notice.setReadCount(0);
        }

        // 如果没有设置过期时间，默认设置为1年后
        if (notice.getExpireTime() == null) {
            notice.setExpireTime(LocalDateTime.now().plusYears(1));
        }

        return save(notice);
    }

    @Override
    @Transactional
    public boolean withdrawNotice(Long noticeId) {
        SystemNotice notice = getById(noticeId);
        if (notice == null) {
            throw new BusinessException(ResultCode.DATA_NOT_FOUND, "公告不存在");
        }

        if (notice.getPublishStatus() != 1) {
            throw new BusinessException(ResultCode.OPERATION_ERROR, "只能撤回已发布的公告");
        }

        LambdaUpdateWrapper<SystemNotice> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SystemNotice::getId, noticeId)
                    .set(SystemNotice::getPublishStatus, 2);

        return update(updateWrapper);
    }

    @Override
    @Transactional
    public boolean setTopNotice(Long noticeId, Integer isTop) {
        SystemNotice notice = getById(noticeId);
        if (notice == null) {
            throw new BusinessException(ResultCode.DATA_NOT_FOUND, "公告不存在");
        }

        LambdaUpdateWrapper<SystemNotice> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SystemNotice::getId, noticeId)
                    .set(SystemNotice::getIsTop, isTop);

        return update(updateWrapper);
    }

    @Override
    public Page<SystemNotice> getUserNotices(Long userId, Integer current, Integer size, 
                                           Integer noticeType, String keyword) {
        Page<SystemNotice> page = new Page<>(current, size);
        LambdaQueryWrapper<SystemNotice> wrapper = new LambdaQueryWrapper<>();
        
        // 只查询已发布的公告
        wrapper.eq(SystemNotice::getPublishStatus, 1);
        
        // 检查有效期
        LocalDateTime now = LocalDateTime.now();
        wrapper.and(w -> w.isNull(SystemNotice::getExpireTime)
                        .or().ge(SystemNotice::getExpireTime, now));
        
        // 按类型筛选
        if (noticeType != null && noticeType > 0) {
            wrapper.eq(SystemNotice::getNoticeType, noticeType);
        }
        
        // 关键字搜索
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(SystemNotice::getTitle, keyword)
                           .or().like(SystemNotice::getContent, keyword));
        }
        
        // 排序：置顶 > 优先级 > 发布时间
        wrapper.orderByDesc(SystemNotice::getIsTop)
               .orderByDesc(SystemNotice::getPriority)
               .orderByDesc(SystemNotice::getPublishTime);
        
        return page(page, wrapper);
    }

    @Override
    public Page<SystemNotice> getAdminNotices(Integer current, Integer size, 
                                            Integer noticeType, Integer publishStatus, String keyword) {
        Page<SystemNotice> page = new Page<>(current, size);
        LambdaQueryWrapper<SystemNotice> wrapper = new LambdaQueryWrapper<>();
        
        // 按类型筛选
        if (noticeType != null && noticeType > 0) {
            wrapper.eq(SystemNotice::getNoticeType, noticeType);
        }
        
        // 按发布状态筛选
        if (publishStatus != null) {
            wrapper.eq(SystemNotice::getPublishStatus, publishStatus);
        }
        
        // 关键字搜索
        if (StringUtils.hasText(keyword)) {
            wrapper.and(w -> w.like(SystemNotice::getTitle, keyword)
                           .or().like(SystemNotice::getContent, keyword));
        }
        
        // 排序
        wrapper.orderByDesc(SystemNotice::getCreateTime);
        
        return page(page, wrapper);
    }

    @Override
    public List<SystemNotice> getNoticesByTargetType(Integer targetUserType) {
        LambdaQueryWrapper<SystemNotice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemNotice::getPublishStatus, 1);
        
        // 检查有效期
        LocalDateTime now = LocalDateTime.now();
        wrapper.and(w -> w.isNull(SystemNotice::getExpireTime)
                        .or().ge(SystemNotice::getExpireTime, now));
        
        wrapper.orderByDesc(SystemNotice::getIsTop)
               .orderByDesc(SystemNotice::getPriority)
               .orderByDesc(SystemNotice::getPublishTime);
        
        return list(wrapper);
    }

    @Override
    public List<SystemNotice> getTopNotices() {
        LambdaQueryWrapper<SystemNotice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemNotice::getPublishStatus, 1)
               .eq(SystemNotice::getIsTop, 1);
        
        // 检查有效期
        LocalDateTime now = LocalDateTime.now();
        wrapper.and(w -> w.isNull(SystemNotice::getExpireTime)
                        .or().ge(SystemNotice::getExpireTime, now));
        
        wrapper.orderByDesc(SystemNotice::getPriority)
               .orderByDesc(SystemNotice::getPublishTime);
        
        return list(wrapper);
    }

    @Override
    public List<SystemNotice> getLatestNotices(Integer limit) {
        LambdaQueryWrapper<SystemNotice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemNotice::getPublishStatus, 1);
        
        // 检查有效期
        LocalDateTime now = LocalDateTime.now();
        wrapper.and(w -> w.isNull(SystemNotice::getExpireTime)
                        .or().ge(SystemNotice::getExpireTime, now));
        
        wrapper.orderByDesc(SystemNotice::getPublishTime)
               .last("LIMIT " + limit);
        
        return list(wrapper);
    }

    @Override
    public Long countUnreadNotices(Long userId) {
        // 获取用户可见的公告
        LambdaQueryWrapper<SystemNotice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemNotice::getPublishStatus, 1);
        
        // 检查有效期
        LocalDateTime now = LocalDateTime.now();
        wrapper.and(w -> w.isNull(SystemNotice::getExpireTime)
                        .or().ge(SystemNotice::getExpireTime, now));
        
        List<SystemNotice> notices = list(wrapper);
        
        // 统计未读数量
        long unreadCount = 0;
        for (SystemNotice notice : notices) {
            if (!noticeReadRecordService.hasRead(notice.getId(), userId)) {
                unreadCount++;
            }
        }
        
        return unreadCount;
    }

    @Override
    public boolean isNoticeValid(SystemNotice notice) {
        if (notice == null || notice.getPublishStatus() != 1) {
            return false;
        }
        
        LocalDateTime now = LocalDateTime.now();
        return notice.getExpireTime() == null || notice.getExpireTime().isAfter(now) || notice.getExpireTime().isEqual(now);
    }

    @Override
    @Transactional
    public boolean increaseReadCount(Long noticeId) {
        LambdaUpdateWrapper<SystemNotice> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SystemNotice::getId, noticeId)
                    .setSql("read_count = read_count + 1");
        
        return update(updateWrapper);
    }

    @Override
    public SystemNotice getNoticeDetail(Long noticeId, Long userId) {
        SystemNotice notice = getById(noticeId);
        if (notice == null) {
            throw new BusinessException(ResultCode.DATA_NOT_FOUND, "公告不存在");
        }
        
        // 记录阅读
        if (userId != null) {
            noticeReadRecordService.recordRead(noticeId, userId);
            increaseReadCount(noticeId);
        }
        
        return notice;
    }
}
